package com.supor.aiot.home.ui.device.config;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.Util;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.MediaManager;
import com.supor.aiot.common.helper.WifiStationManager;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ActivityInputWifiBinding;
import com.supor.aiot.home.helper.DataCache;
import com.supor.nfc.lib.utils.NfcUtils;

import androidx.core.content.ContextCompat;

import static com.supor.aiot.common.app.Constants.REQUEST_CODE;
import static com.supor.aiot.common.app.Constants.SETTING_AP;
import static com.supor.aiot.common.app.Constants.SETTING_GPS;
import static com.supor.aiot.common.app.Constants.SETTING_WIFI;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: WiFi输入页 <br>
 * 作者: lei <br>
 * 日期: 2020/11/30 <br>
 */
@Route(path = PathUrl.PATH_INPUT_WIFI)
public class InputWiFiActivity extends BaseConfigActivity<NoViewModel, ActivityInputWifiBinding> {
    private boolean isApMode = false;
    /**
     * 1-GPS close|2-wifi close|3-wifi disconnect|4-wifi no access|5-has illegal char|6-no permission
     */
    private int wifiStatus = 0;
    private RxPermissions rxPermissions;
    /**
     * 是否已进入配置
     */
    private boolean isConfig = false;
    /**
     * 是否需要弹框
     */
    private boolean isNeedPop = true;
    private int retry = 0;
    PermissionsChecker permissionsChecker;
    private ProductType.ProductModel productModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        rxPermissions = new RxPermissions(this);
        permissionsChecker = new PermissionsChecker(this);
        Intent intent = getIntent();
        if (intent != null) {
            productModel = (ProductType.ProductModel) intent.getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
            }
        }
        // initView();
        // checkLocationPermission();
        // Logc.e("action: " + getIntent().getAction());
        checkWiFiStatus();
        if (!AppAgent.isLogin()) {
            SuporPresenter.getInstance().displayLogin(false);
        }
    }

    @Override
    protected int resourceId() {
        return R.layout.activity_input_wifi;
    }

    public void initView() {
        super.initView();
        bindingView.setViewM(this);
        bindingView.bindWifiMain.setViewM(this);
        bindingView.toolbar.setIvLeftOnClickListener(v -> {
            if (AppAgent.isShowCmcc) {
                return;
            }
            finish();
        });
        bindingView.toolbar.setTvLeftOnClickListener(v -> {
            if (AppAgent.isShowCmcc) {
                return;
            }
            finish();
        });
        bindingView.btnNextStep.setText(R.string.next_step);
        bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
        bindingView.llRememberPass.setVisibility(View.GONE);
        bindingView.btnNextStep.setEnabled(false);
        bindingView.bindWifiMain.etSsid.setEnabled(false);
        try {
            bindingView.bindWifiMain.etSsid.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (s.length() > 0) {
                        bindingView.btnNextStep.setEnabled(true);
                    } else {
                        bindingView.btnNextStep.setEnabled(false);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {}
            });
            bindingView.bindWifiMain.etPassword.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (Util.hasChineseChar(s.toString())) {
                        tips(getResources().getString(R.string.bind_wifi_pass_no_chinese));
                        bindingView.btnNextStep.setEnabled(false);
                    } else {
                        bindingView.btnNextStep.setEnabled(true);
                    }
                    if ((s.length() >= 8 || s.length() ==
                    0) && !getString(R.string.bind_wifi_loading).equalsIgnoreCase(bindingView.bindWifiMain.tvSsidSetting.getText().toString())) {
                        bindingView.btnNextStep.setEnabled(true);
                    } else {
                        bindingView.btnNextStep.setEnabled(false);
                    }
                    if (!WifiStationManager.getInstance().isWifiConnected() && !isApMode) {
                        bindingView.btnNextStep.setEnabled(false);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
            bindingView.bindWifiMain.etPassword.setFilters(new InputFilter[]{
                    (source, start, end, dest, dstart, dend) -> {
                        if (Util.hasChineseChar(source.toString())) {
                            tips(getResources().getString(R.string.bind_wifi_pass_no_chinese));
                            return "";
                        } else
                            return source;
                    }
            });

        } catch (Exception e) {
            e.printStackTrace();
            tips(e.getMessage());
        }

        bindingView.llRememberPass.setSelected(false);
        bindingView.tvSlideTip.setOnClickListener(v ->
                bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.llRememberPass.setOnClickListener(v ->
                bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.slideBtn.setOnSlideButtonChangeListener((view, isOpen) -> {
            bindingView.tvSlideTip.setSelected(isOpen);
            bindingView.llRememberPass.setSelected(isOpen);
            String ssid = bindingView.bindWifiMain.etSsid.getInputText();
            if (!TextUtils.isEmpty(ssid)) {
                if (!isOpen) {
                    DataCache.removeWifi(ssid);
                }
            }
        });

        bindingView.bindWifiMain.cbHidePass.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                //选择状态 显示明文--设置为可见的密码
                //mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                //第二种
                bindingView.bindWifiMain.etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType
                // .TYPE_TEXT_VARIATION_PASSWORD
                //mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType
                // .TYPE_TEXT_VARIATION_PASSWORD);
                //第二种
                bindingView.bindWifiMain.etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            Util.setEditTextCursorEnd(bindingView.bindWifiMain.etPassword);

        });
        bindingView.btnNextStep.setOnLongClickListener(v -> {
            if (!AppAgent.isLogin()) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                return false;
            }
            if (wifiStatus != 0) {
                return false;
            }
            String ssid = bindingView.bindWifiMain.etSsid.getInputText();
            if (ssid.length() < 1) {
                tips(getResources().getString(R.string.bind_wifi_ssid_not_over_0));
                return false;
            }
            String pass = bindingView.bindWifiMain.etPassword.getInputText();
            Bundle bundle = getIntent().getExtras();
            if (bundle == null) {
                bundle = new Bundle();
            }
            bundle.putString(Constants.Key.SSID, ssid);
            bundle.putString(Constants.Key.PASS, pass);
            String bssid = WifiStationManager.getInstance().getCurrentWifiBSSID();
            Util.isValidMac(bssid);
            if (bssid != null) {
                bundle.putString(Constants.Key.BSSID, bssid.replace(":", ""));
            }
            DataCache.CURRENT_SSID = ssid;
            DataCache.CURRENT_PWD = pass;
            if (bindingView.slideBtn.isOpen()) {
                DataCache.cacheWifi(ssid, pass);
            }

            Intent intent;
            bundle.putInt(Constants.Key.CONFIG_TYPE, 1);
            intent = new Intent(InputWiFiActivity.this, NetGuideActivity.class);
            intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUEST_CODE);
            isConfig = true;
            return false;
        });

        if (NfcUtils.NFC_STATE == 0) {
            bindingView.toolbar.setLeftText(getString(R.string.nfc_config_title));
            bindingView.topView.setConfig2Text(getString(R.string.nfc_touch));
            bindingView.llAp.setVisibility(View.VISIBLE);
        } else {
            bindingView.llAp.setVisibility(View.GONE);
            bindingView.toolbar.setLeftText(getString(R.string.bind_net_guide));
            bindingView.topView.setConfig2Text(getString(R.string.top_start_ap));
        }
    }

    /**
     * 检查WiFi状态，步骤如下：
     * 1.检查GPS是否打开：未打开则弹框提示用户打开，取消-底部按钮置为设置，点击跳转GPS页面，
     * 确认-跳转GPS页面，若未打开返回则继续弹框
     * ## 逻辑调整，权限检测从进页面检测改为此处第(2)步检测
     * (2) 检测权限
     * ## 逻辑调整，权限检测从进页面检测改为此处第(3)步检测
     * (3) 检测手机热点打开步骤
     * 2.检查WiFi是否打开：未打开则文字提示，底部按钮置为链接WiFi网络
     * 3.检查WiFi是否链接：未链接则文字提示，底部按钮置为链接WiFi网络
     * 4.检查WiFi是否能访问外网
     */
    private void checkWiFiStatus() {
        isApMode = WifiStationManager.isWifiApOpen(this);
        // bindingView.bindWifiMain.etSsid.setEnabled(isApMode);
        if (!SystemUtils.isGpsEnabled(this)) {
            // btnNextStep.setEnabled(false);
            wifiStatus = 1;
            bindingView.btnNextStep.setEnabled(true);
            bindingView.btnNextStep.setText(R.string.go_settings);
            bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
            bindingView.llRememberPass.setVisibility(View.GONE);
            bindingView.tvStatus.setVisibility(View.VISIBLE);
            bindingView.tvStatus.setText(R.string.bind_wifi_turn_on_gps_msg);
            if (isNeedPop) {
                showDialog(getResources().getString(R.string.bind_wifi_turn_on_gps_title),
                        getResources().getString(R.string.bind_wifi_turn_on_gps_msg),
                        getResources().getString(R.string.go_settings),
                        (dialog, which) -> {
                            ActivityHelper.gotoGpsSetting(InputWiFiActivity.this, SETTING_GPS);
                            dialog.dismiss();
                        },
                        getResources().getString(R.string.cancel),
                        (dialog, which) -> {
                            dialog.dismiss();
                        });
            }
        } else if (permissionsChecker.lacksPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            wifiStatus = 6;
            bindingView.btnNextStep.setEnabled(true);
            bindingView.btnNextStep.setText(R.string.go_settings);
            bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
            bindingView.llRememberPass.setVisibility(View.GONE);
            bindingView.tvStatus.setVisibility(View.VISIBLE);
            bindingView.tvStatus.setText(R.string.bind_wifi_turn_on_gps_msg);
            checkLocationPermission();
        }/* else if (isApMode) {
            displayWifi();
        }*/ else if (!WifiStationManager.getInstance().isWifiEnabled()) {
            String tip = getString(R.string.bind_wifi_status_1);
            SpannableString spanStr = new SpannableString(tip);
            spanStr.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)),
                    tip.indexOf("家庭Wi-Fi"), tip.indexOf("家庭Wi-Fi") + 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            wifiStatus = 2;
            bindingView.btnNextStep.setEnabled(true);
            bindingView.btnNextStep.setText(R.string.bind_btn_status_1);
            bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
            bindingView.llRememberPass.setVisibility(View.GONE);
            bindingView.tvStatus.setVisibility(View.VISIBLE);
            bindingView.tvStatus.setText(spanStr);
        } else if (!WifiStationManager.getInstance().isWifiConnected()) {
            String tip = getString(R.string.bind_wifi_status_2);
            SpannableString spanStr = new SpannableString(tip);
            spanStr.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)),
                    tip.indexOf("家庭Wi-Fi"), tip.indexOf("家庭Wi-Fi") + 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanStr.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)),
                    tip.lastIndexOf("家庭Wi-Fi"), tip.lastIndexOf("家庭Wi-Fi") + 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            wifiStatus = 3;
            bindingView.btnNextStep.setEnabled(true);
            bindingView.btnNextStep.setText(R.string.bind_btn_status_1);
            bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
            bindingView.llRememberPass.setVisibility(View.GONE);
            bindingView.tvStatus.setVisibility(View.VISIBLE);
            bindingView.tvStatus.setText(spanStr);
        } else {
            displayWifi();
        }
    }

    private void displayWifi() {
        if (!isApMode) {
            String ssid = WifiStationManager.getInstance().getCurrentWifiSSID();
            Logc.i("displayWifi: " + ssid);
            if (ssid == null) {
                checkWiFiStatus();
                return;
            }
            if (ssid.contains("unknown ssid") && retry < 6) {
                Logc.i("checkWiFiStatus: retry---" + retry);
                retry++;
                new Handler().postDelayed(this::checkWiFiStatus, 500);
                return;
            }
            bindingView.bindWifiMain.etSsid.setText(ssid);
            String pwd = DataCache.getWifiPwd(ssid);
            if (!TextUtils.isEmpty(pwd)) {
                bindingView.bindWifiMain.etPassword.setText(pwd);
                Util.setEditTextCursorEnd(bindingView.bindWifiMain.etPassword);
            } else {
                bindingView.bindWifiMain.etPassword.setText("");
                // btnNextStep.setEnabled(false);
            }
            bindingView.bindWifiMain.ivSsid.setImageResource(R.mipmap.bind_wifi_ssid);
            bindingView.bindWifiMain.tvSsidSetting.setText(R.string.bind_wifi_loading);
            bindingView.bindWifiMain.etPassword.setHint(R.string.bind_input_pass);
            bindingView.llAp.setVisibility(View.VISIBLE);
        } else {
            // bindingView.bindWifiMain.ivSsid.setImageResource(R.mipmap.bind_ap_wifi_ssid);
            // bindingView.bindWifiMain.etSsid.setText("");
            // bindingView.bindWifiMain.etSsid.setHint(R.string.bind_input_ap_ssid);
            // bindingView.bindWifiMain.etPassword.setHint(R.string.bind_input_ap_pass);
            // bindingView.bindWifiMain.tvSsidSetting.setText("");
            // closeDialog();
            // bindingView.llAp.setVisibility(View.GONE);
            // bindingView.tvStatus.setVisibility(View.GONE);
            // bindingView.bindWifiMain.rlRoot.setVisibility(View.VISIBLE);
            // bindingView.llRememberPass.setVisibility(View.GONE);
            // bindingView.btnNextStep.setText(R.string.next_step);
            // bindingView.btnNextStep.setEnabled(true);
            // wifiStatus = 0;
            // return;
        }
        // delete on 2021/02/22 by lei
        /*if (Util.hasChineseChar(ssid) || Util.hasSpaceChar(ssid)) {
            wifiStatus = 5;
            showIllegalCharDialog();
            return;
        }*/
        closeDialog();
        bindingView.tvStatus.setVisibility(View.GONE);
        bindingView.bindWifiMain.rlRoot.setVisibility(View.VISIBLE);
        bindingView.llRememberPass.setVisibility(View.VISIBLE);
        bindingView.btnNextStep.setText(R.string.next_step);
        bindingView.btnNextStep.setEnabled(false);

        ThreadUtils.execute(() -> {
            // Logc.d("start ping-------------------");
            // boolean isAccess = WifiStationManager.ping3("14.215.177.38", 1, 3000);
            boolean isAccess = WifiStationManager.ping2("www.baidu.com", 3, 10);
            // Logc.d("end ping-------------------");
            if (!isAccess) {
                runOnUiThread(() -> {
                    wifiStatus = 4;
                    bindingView.btnNextStep.setEnabled(true);
                    bindingView.btnNextStep.setText(R.string.bind_btn_status_1);
                    bindingView.bindWifiMain.tvSsidSetting.setText(R.string.bind_wifi_unavailable);
                });
            } else {
                runOnUiThread(() -> {
                    wifiStatus = 0;
                    if (bindingView.bindWifiMain.etPassword.getInputText().length() >= 8 || bindingView.bindWifiMain.etPassword.getInputText().length() == 0) {
                        bindingView.btnNextStep.setEnabled(true);
                    } else {
                        bindingView.btnNextStep.setEnabled(false);
                    }
                    bindingView.btnNextStep.setText(R.string.next_step);
                    bindingView.bindWifiMain.tvSsidSetting.setText(R.string.bind_change_wifi);
                });
                if (TextUtils.isEmpty(DataCache.GIZ_IP)) {
                    DataCache.getGIZIp();
                }
            }
            if (Constants.USE_VOICE) {
                MediaManager.getInstance().stopMediaPlayer();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isConfig = false;
        String ssid = WifiStationManager.getInstance().getCurrentWifiSSID();
        if (ssid != null && !ssid.contains("unknown ssid")) {
            bindingView.bindWifiMain.etSsid.setText(ssid);
        }
    }

    /**
     * 检查定位权限
     */
    @SuppressLint({"CheckResult", "AutoDispose"})
    private void checkLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            //表示用户同意权限
                            checkWiFiStatus();
                            RxBus3.getInstance().post(Constants.Tag.LOCATION_PERMISSION, Constants.Value.SUCCESS);
                        } else {
                            //表示用户不同意权限
                            Logc.i("request location failed");
                            // tips(getResources().getString(R.string.bind_loc_permission_faild));
                            showLocationPermissionRequestFailed();
                        }
                    });
        } else {
            checkWiFiStatus();
        }
    }

    @Override
    public void updateNetStatus(int type) {
        super.updateNetStatus(type);
        if (isConfig) {
            return;
        }
        checkWiFiStatus();
    }

    @Override
    public void updateWifiStatus(int state) {
        super.updateWifiStatus(state);
        if (state != WifiManager.WIFI_STATE_ENABLED
                && state != WifiManager.WIFI_STATE_DISABLED) {
            return;
        }
        if (isConfig) {
            return;
        }
        checkWiFiStatus();
    }

    private void showIllegalCharDialog() {
        closeDialog();
        showDialog(getResources().getString(R.string.bind_wifi_reselect),
                getResources().getString(R.string.bind_wifi_illegal_char),
                getResources().getString(R.string.return_back),
                (dialog, which) -> {
                    ActivityHelper.gotoWiFiSetting(this);
                    // dialog.dismiss();
                });
    }

    private void jumpToNextActivity(String pass) {
        if (wifiStatus == 1) {
            ActivityHelper.gotoGpsSetting(InputWiFiActivity.this, SETTING_GPS);
        } else if (wifiStatus == 2) {
            ActivityHelper.gotoWiFiSetting(this);
            if (Constants.USE_VOICE) {
                ThreadUtils.execute(() -> MediaManager.getInstance().voiceTip("voice4.mp3"));
            }
        } else if (wifiStatus == 3) {
            ActivityHelper.gotoWiFiSetting(this);
            if (Constants.USE_VOICE) {
                ThreadUtils.execute(() -> MediaManager.getInstance().voiceTip("voice5.mp3"));
            }
        } else if (wifiStatus == 5) {
            showIllegalCharDialog();
        } else if (wifiStatus == 6) {
            ActivityHelper.startAppSettings(InputWiFiActivity.this,
                    Constants.REQUEST_CODE2);
        } else if (wifiStatus != 0) {
            ActivityHelper.gotoWiFiSetting(this);
        } else {
            if (Util.hasChineseChar(pass)) {
                tips(getResources().getString(R.string.bind_wifi_pass_no_chinese));
                return;
            } else if (pass.length() > 0 && pass.length() < 8) {
                tips(getResources().getString(R.string.bind_wifi_pass_not_over_8));
                return;
            }/* else if (isApMode && pass.length() < 8) {
                tips(getResources().getString(R.string.bind_wifi_pass_not_over_8));
            }*/
            String ssid = bindingView.bindWifiMain.etSsid.getInputText();
            if (ssid.length() < 1) {
                tips(getResources().getString(R.string.bind_wifi_ssid_not_over_0));
                return;
            }
            Bundle bundle = getIntent().getExtras();
            if (bundle == null) {
                bundle = new Bundle();
            }

            // Logc.e("input routerSsid= " + ssid + ", routerPwd= " + pass);
            bundle.putString(Constants.Key.SSID, ssid);
            bundle.putString(Constants.Key.PASS, pass);
            String bssid = WifiStationManager.getInstance().getCurrentWifiBSSID();
            Util.isValidMac(bssid);
            if (bssid != null) {
                bundle.putString(Constants.Key.BSSID, bssid.replace(":", ""));
            }
            DataCache.CURRENT_SSID = ssid;
            DataCache.CURRENT_PWD = pass;

            Intent intent;
            int type = bundle.getInt(Constants.Key.CONFIG_TYPE, -1);
            if (type == 0 || NfcUtils.NFC_STATE != 1) { // todo
                bundle.putInt(Constants.Key.CONFIG_TYPE, 0);
                intent = new Intent(this, NFCGuideActivity.class);
            } else {
                bundle.putInt(Constants.Key.CONFIG_TYPE, 1);
                intent = new Intent(this, NetGuideActivity.class);
            }
            intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUEST_CODE);
            isConfig = true;
            if (bindingView.slideBtn.isOpen()) {
                DataCache.cacheWifi(ssid, pass);
            } else {
                DataCache.removeWifi(ssid);
                bindingView.bindWifiMain.etPassword.setText("");
                bindingView.btnNextStep.setEnabled(false);
            }
        }
    }

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_ssid_setting) {
            if (AppAgent.isShowCmcc) {
                return;
            }
            ActivityHelper.gotoWiFiSetting(this);
        } else if (id == R.id.btn_next_step) {
            if (AppAgent.isShowCmcc) {
                return;
            }
            if (!AppAgent.isLogin()) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                return;
            }
            jumpToNextActivity(bindingView.bindWifiMain.etPassword.getInputText());
        } else if (id == R.id.btn_cancel) {
            if (AppAgent.isShowCmcc) {
                return;
            }
            finish();
        } else if (id == R.id.tv_5G_hint || id == R.id.tv_5G_hint_1080) {
            // startActivity(new Intent(this, WiFiQuestionActivity.class));
        } else if (id == R.id.tv_ap) {
            if (!AppAgent.isLogin()) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                return;
            }
            Intent intent = new Intent(InputWiFiActivity.this, NFCApGuideActivity.class);
            Bundle bundle = getIntent().getExtras();
            if (bundle == null) {
                bundle = new Bundle();
            }
            intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
            intent.putExtras(bundle);
            startActivityForResult(intent, SETTING_AP);
            isConfig = true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (SETTING_GPS == requestCode) {
            if (!SystemUtils.isGpsEnabled(this)) {
                // tips(getResources().getString(R.string.bind_open_loc_faild));
                wifiStatus = 1;
                bindingView.btnNextStep.setEnabled(true);
                bindingView.btnNextStep.setText(R.string.go_settings);
                bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
                bindingView.llRememberPass.setVisibility(View.GONE);
                bindingView.tvStatus.setVisibility(View.VISIBLE);
                bindingView.tvStatus.setText(R.string.bind_wifi_turn_on_gps_msg);
            } else {
                RxBus3.getInstance().post(Constants.Tag.LOCATION_PERMISSION, Constants.Value.SUCCESS);
                checkWiFiStatus();
            }
        } else if (SETTING_WIFI == requestCode) {
            checkWiFiStatus();
        } else if (Constants.REQUEST_CODE == requestCode) {
            isNeedPop = false;
            checkWiFiStatus();
            if (resultCode == 1) {
                bindingView.bindWifiMain.cbHidePass.setChecked(true);
            }
        } else if (requestCode == Constants.REQUEST_CODE2) {

            if (!permissionsChecker.lacksPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                Logc.i("permission request: success");
                RxBus3.getInstance().post(Constants.Tag.LOCATION_PERMISSION, Constants.Value.SUCCESS);
                checkWiFiStatus();
            }
        } else if (requestCode == SETTING_AP) {
            if (resultCode == Constants.RESULT_CODE) {
                bindingView.bindWifiMain.etPassword.setText("");
                bindingView.bindWifiMain.etSsid.setText("");
            }
            checkWiFiStatus();
        }
    }

    private void showLocationPermissionRequestFailed() {
        showDialog(getString(R.string.permission_location_title),
                getString(R.string.permission_location_msg),
                getString(R.string.go_settings), (dialog, which) -> {
                    ActivityHelper.startAppSettings(InputWiFiActivity.this,
                            Constants.REQUEST_CODE2);
                    dialog.dismiss();
                },
                getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
    }

}
